package com.hjh.thymeleafdemo1.web;

import com.hjh.thymeleafdemo1.Service.UserService;
import com.hjh.thymeleafdemo1.entity.User;
import com.hjh.thymeleafdemo1.repository.UserRepository;
import com.hjh.thymeleafdemo1.web.component.Constants;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Resource
    private UserService userService;

    @RequestMapping({"/toLogin", "/"})
    public String login() {
        return "login";
    }

    @RequestMapping(value = "/doLogin")
    public String dologin(String name, String password, HttpServletRequest request){
        User user = userService.login(name,password);
        if (user != null){
            request.getSession().setAttribute("loginUser",user);
            return "redirect:/user/toIndex";
        }else {
            request.setAttribute("message","登录失败，用户名或密码错误！");
            return "login";
        }
    }

    //注销
    @RequestMapping(value = "/logout")
    public String logout(HttpSession session){
        //清除session
        session.removeAttribute(Constants.USER_SESSION);
        return "login";
    }
}
